package dictionary;


import util.ArrayHelper;
import util.AssertUtils;
import util.ClassHelper;

/**
 * 
 * 字典枚举帮助类
 *
 * @author:
 *		唐竹
 * @date 
 *		创建时间：2011-6-30 下午04:14:53 
 *
 */
public class DictionaryUtils {

	/**
	 * 
	 * 	通过编码 获得字典枚举，code为String时大小写敏感
	 *
	 *	@param code				字典编码，不能为null
	 *	@param dictionaryClass	字典枚举类型，不能为null
	 *
	 *	@return 
	 *		E	字典枚举，Code错误时返回null
	 *
	 * 	@throws 
	 *		IllegalArgumentException - 当code为null时抛出
	 *
	 * 	@log
	 *		<YYYY-MM-DD			变更者		变更内容>
	 *		2011-6-30			 唐竹			创建
	 */
	@SuppressWarnings("unchecked")
	public static <E extends Dictionary, T extends Object> E getByCode(T code, Class<?> dictionaryClass) {
		AssertUtils.notNull(code, "The dictionary code not should be null!");
		AssertUtils.notNull(dictionaryClass, "The dictionary class not should be null!");

		Object[] dictionaries = dictionaryClass.getEnumConstants();
		if (!ArrayHelper.isEmpty(dictionaries)) {
			for (Object e : dictionaries) {
				E dictionary = (E) e;
				Object dictionaryCode = dictionary.getCode();
				if (dictionaryCode == null)
					return null;

				if (dictionaryCode.equals(code))
					return dictionary;
				if (code instanceof String && dictionaryCode.toString().equals(code))
					return dictionary;
			}
		}
		return null;
	}

	/**
	 * 
	 * 	字典枚举ToString方法，输出格式为：枚举值[code,describe]
	 *
	 * 	@log
	 *		<YYYY-MM-DD			变更者		变更内容>
	 *		2011-6-30			 唐竹			创建
	 */
	@SuppressWarnings("unchecked")
	public static <E extends Dictionary> String toString(E e) {
		StringBuffer toString = new StringBuffer();
		if (e != null) {
			toString.append(ClassHelper.getShortName(e.getClass())).append('[').append(e.getCode()).append(',').append(
					e.getDescribe()).append(']');
		}
		return toString.toString();
	}
}
